<template>
  <div class="app-container">
    <v-row justify="center">
      <v-dialog
        v-model="visible"
        persistent
        transition="dialog-top-transition"
        max-width="600px">

        <v-card>
          <!-- 对话框标题 -->
          <v-card-title>
            <span style="font-size: 18px">新增用户</span>
          </v-card-title>

          <!-- 表单 -->
          <v-form ref="form" v-model="valid">
            <v-card-text>
              <v-container>
                <v-row>
                  <v-col cols="12" sm="6">
                    <v-text-field
                      v-model="form.nickName"
                      :rules="rules.nickName"
                      label="*用户昵称"
                      placeholder="请输入用户昵称"
                      required
                      clearable
                      dense
                      autofocus
                    ></v-text-field>
                  </v-col>

                  <v-col cols="12" sm="6">
                    <v-menu
                      ref="menu"
                      v-model="showDeptOption"
                      transition="scale-transition"
                      offset-y
                      max-width="270px"
                      min-width="auto"
                      style="padding: 0"
                    >
                      <template v-slot:activator="{ on, attrs }">
                        <v-text-field
                          v-model="form.deptName"
                          label="归属部门"
                          placeholder="请选择归属部门"
                          v-bind="attrs"
                          v-on="on"
                          dense
                          style="padding: 0"
                        ></v-text-field>
                      </template>
                      <v-treeview
                        ref="tree"
                        dense
                        activatable
                        hoverable
                        return-object
                        :items="deptOptions" style="font-size: 14px;padding: 0;background-color: white;min-width: 250px !important;max-height: 500px;overflow: auto;"
                      >
                        <!-- 插槽 -->
                        <template v-slot:prepend="{ item, open }">
                          <div @click="handleNodeClick(item)">
                            {{ item.label }}
                          </div>
                        </template>
                      </v-treeview>
                    </v-menu>
                  </v-col>

                  <v-col cols="12" sm="6">
                    <v-text-field
                      v-model="form.phoneNumber"
                      label="手机号码"
                      placeholder="请输入手机号码"
                      :rules="[rules.phoneNumber]"
                      counter="11"
                      clearable
                      dense
                    ></v-text-field>
                  </v-col>

                  <v-col cols="12" sm="8" md="6">
                    <v-text-field
                      v-model="form.email"
                      label="邮箱"
                      placeholder="请输入邮箱"
                      :rules="[rules.email]"
                      counter="50"
                      clearable
                      dense
                      hint="xxx@example.com"
                    ></v-text-field>
                  </v-col>

                  <v-col cols="12" sm="6">
                    <v-text-field
                      v-model="form.userName"
                      :rules="rules.userName"
                      label="*用户名称"
                      placeholder="请输入用户名称"
                      required
                      clearable
                      dense
                    ></v-text-field>
                  </v-col>
                  <v-col cols="12" sm="6">
                    <v-text-field
                      v-model="form.password"
                      :rules="rules.password"
                      label="*用户密码"
                      placeholder="请输入用户密码"
                      type="password"
                      required
                      clearable
                      dense
                      prepend-inner-icon="mdi-lock"
                    ></v-text-field>
                  </v-col>
                  <v-col cols="12" sm="6">
                    <v-select
                      v-model="form.sex"
                      placeholder="请选择"
                      :items="sexOptions"
                      item-text="dictLabel"
                      item-value="dictValue"
                      label="用户性别"
                      clearable
                      dense
                    ></v-select>
                  </v-col>
                  <v-col cols="12" sm="6">
                    <v-radio-group
                      label="状态"
                      v-model="form.status"
                      row dense style="margin: 0;"
                    >
                      <v-radio
                        v-for="dict in statusOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                      ></v-radio>
                    </v-radio-group>
                  </v-col>

                  <!-- 岗位 多选 -->
                  <v-col cols="12" sm="6">
                    <v-select
                      v-model="form.postIds"
                      placeholder="请选择"
                      :items="postOptions"
                      item-text="postName"
                      item-value="postId"
                      label="岗位"
                      multiple
                      clearable
                      dense
                    ></v-select>
                  </v-col>

                  <!-- 角色 多选 -->
                  <!-- todo 禁用 -->
                  <v-col cols="12" sm="6">
                    <v-select
                      v-model="form.roleIds"
                      placeholder="请选择"
                      :items="roleOptions"
                      item-text="roleName"
                      item-value="roleId"
                      label="角色"
                      multiple
                      clearable
                      dense
                    ></v-select>
                  </v-col>

                  <v-col cols="12" sm="12" style="padding-bottom: 0;padding-top: 0">
                    <v-textarea
                      v-model="form.remark"
                      label="备注"
                      placeholder="请输入内容"
                      auto-grow
                      filled
                      clearable
                      dense
                    >
                    </v-textarea>
                  </v-col>
                </v-row>
              </v-container>
              <small class="ml10">*表示必需字段</small>
            </v-card-text>
          </v-form>

          <!-- 底部操作按钮 -->
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn
              text
              @click="updateVisible(false)">
              取消
            </v-btn>
            <v-btn
              color="blue darken-1"
              text
              @click="submitForm">
              保存
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
  </div>
</template>

<!-- 新增用户对话框 -->
<script>
  import { getUser, addUser, updateUser } from "@/api/system/user";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "UserAddComp",
    props: {
      visible: Boolean, // 是否打开对话框
      deptOptions: Array, // 部门树选项
      sexOptions: Array, // 性别状态字典
      statusOptions: Array, // 状态数据字典
      postOptions: Array, // 岗位选项
      roleOptions: Array, // 角色选项
    },
    emits: ['updateVisible'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          nickName: [
            val => (val || '').length > 0 || '用户昵称不能为空'
          ],
          userName: [
            val => (val || '').length > 0 || '用户名称不能为空'
          ],
          password: [
            val => (val || '').length > 0 || '用户密码不能为空'
          ],
          email: value => {
            if (value) {
              const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
              return pattern.test(value) || '无效的电子邮件'
            }
          },
          phoneNumber: value => {
            if (value) {
              const pattern = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/
              return pattern.test(value) || '请输入正确的手机号码'
            }
          }
        },
        valid: false,
        // 是否显示部门选择
        showDeptOption: false,
      };
    },
    methods: {
      // 部门节点单击事件
      handleNodeClick(data) {
        if (data) {
          this.form.deptId = data.id;
          this.form.deptName = data.label;
        }
      },
      validate () {
        this.$refs.form.validate()
      },
      /** 保存按钮 */
      async submitForm() {
        this.$store.commit("snackbar/CLOSE_SNACKBAR");
        await this.validate();
        if (this.valid) {
          addUser(this.form).then(res => {
            // 使用全局消息提示
            this.$store.dispatch('snackbar/openSnackbar',{
              msg: '新增成功',
              color: 'success'
            })
            this.$emit('done');
            this.updateVisible(false);
          });
        }
      },
      // 调用父级关闭对话框, 并重置表单
      updateVisible(value) {
        this.reset();
        this.$emit('updateVisible', value);
      },
      // 表单重置
      reset() {
        this.form = {
          userId: null,
          deptId: null,
          userName: null,
          nickName: null,
          password: null,
          phonenumber: null,
          email: null,
          sex: null,
          status: "1",
          remark: null,
          postIds: [],
          roleIds: []
        };
        if (this.$refs.form) {
          this.$refs.form.resetValidation();
        }
      },
    }
  };
</script>

<style>
  .v-treeview-node {
    margin-left: -15px !important;
  }
</style>
